package com.common.config;


import org.apache.shiro.codec.Base64;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //4.重写sessionManager
    @Bean
    public DefaultWebSessionManager sessionManager() {
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        // 去掉shiro登录时url里的JSESSIONID
        sessionManager.setSessionIdUrlRewritingEnabled(true);
        return sessionManager;
    }
    //3.创建 ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置完全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro的内置过滤器
        /*
        * · anon： 无需认证就可以访问
        * · authc：必须认证了才能访问
        * user: 必须有记住我功能才能使用
        * perms[某权限]:拥有对某个资源的权限才能访问；
        * role:必须拥有某个角色权限才能访问
        *
        */
        Map<String,String> filterMap = new LinkedHashMap<>();
        filterMap.put("/admin/**","perms[admin]");
        filterMap.put("/com/**","anon");
        //注销功能
        filterMap.put("/logout","logout");
        bean.setFilterChainDefinitionMap(filterMap);
        System.out.println("资源过滤："+filterMap);
//        //设置登录页
        bean.setLoginUrl("/toLogin");
//        //设置未授权页面
        bean.setUnauthorizedUrl("/unauthorized");
        return bean;
    }

    //2.创建 DefaultWebSecurityManager
    @Bean
    DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        securityManager.setRealm(userRealm);
        //设置记住我管理
        securityManager.setRememberMeManager(cookieRememberMeManager());
        return  securityManager;
    }

    //1.创建realm对象

    @Bean
    public CookieRememberMeManager cookieRememberMeManager() {
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
        simpleCookie.setMaxAge(259200000);
        cookieRememberMeManager.setCookie(simpleCookie);
        cookieRememberMeManager.setCipherKey(Base64.decode("6ZmI6I2j5Y+R5aSn5ZOlAA=="));
        return cookieRememberMeManager;
    }

}
